#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 打印信息
info() {
    echo -e "${GREEN}[信息]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[警告]${NC} $1"
}

error() {
    echo -e "${RED}[错误]${NC} $1"
    exit 1
}

# 检查系统要求
check_system() {
    info "检查系统要求..."

    # 检查操作系统
    if [[ "$(uname)" != "Linux" && "$(uname)" != "Darwin" ]]; then
        error "不支持的操作系统: $(uname)"
    fi

    # 检查Go环境
    if ! command -v go &> /dev/null; then
        error "Go未安装，请先安装Go"
    fi

    GO_VERSION=$(go version | awk '{print $3}' | sed 's/go//')
    if [[ "${GO_VERSION}" < "1.21" ]]; then
        error "Go版本过低，需要1.21或更高版本"
    fi

    # 检查Docker
    if ! command -v docker &> /dev/null; then
        error "Docker未安装，请先安装Docker"
    fi

    # 检查Git
    if ! command -v git &> /dev/null; then
        error "Git未安装，请先安装Git"
    }

    info "系统检查通过"
}

# 检查SSH配置
check_ssh() {
    info "检查SSH配置..."

    # 检查SSH密钥
    if [[ ! -f ~/.ssh/id_rsa ]]; then
        warn "SSH密钥不存在，正在生成..."
        ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa -N ""
    fi

    # 检查权限
    if [[ "$(stat -c %a ~/.ssh/id_rsa 2>/dev/null || stat -f %Lp ~/.ssh/id_rsa)" != "600" ]]; then
        warn "修正SSH密钥权限..."
        chmod 600 ~/.ssh/id_rsa
    fi

    info "SSH配置检查完成"
}

# 安装依赖
install_deps() {
    info "安装依赖..."

    # 下载Go依赖
    go mod download || error "依赖下载失败"

    info "依赖安装完成"
}

# 编译程序
build_binary() {
    info "编译程序..."

    # 创建输出目录
    mkdir -p bin

    # 获取版本信息
    VERSION=$(git describe --tags --always --dirty 2>/dev/null || echo "dev")
    GIT_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
    BUILD_TIME=$(date "+%Y-%m-%d %H:%M:%S")

    # 编译
    CGO_ENABLED=0 go build \
        -ldflags "-X main.Version=${VERSION} -X main.BuildTime=${BUILD_TIME} -X main.GitCommit=${GIT_COMMIT}" \
        -o bin/deployer \
        cmd/deployer/main.go || error "编译失败"

    info "编译完成"
}

# 安装程序
install_binary() {
    info "安装程序..."

    # 创建安装目录
    sudo mkdir -p /usr/local/bin || error "创建安装目录失败"

    # 复制程序
    sudo cp bin/deployer /usr/local/bin/ || error "复制程序失败"

    # 设置执行权限
    sudo chmod +x /usr/local/bin/deployer || error "设置权限失败"

    info "安装完成"
}

# 配置环境
setup_env() {
    info "配置环境..."

    # 创建配置目录
    mkdir -p ~/.deployer/{cache,logs,workspace} || error "创建配置目录失败"

    # 配置Shell
    SHELL_RC=""
    if [[ -f ~/.zshrc ]]; then
        SHELL_RC=~/.zshrc
    elif [[ -f ~/.bashrc ]]; then
        SHELL_RC=~/.bashrc
    else
        warn "未找到Shell配置文件"
        return
    fi

    # 添加环境变量
    if [[ -f "${SHELL_RC}" ]]; then
        if ! grep -q "# Deployer Configuration" "${SHELL_RC}"; then
            echo -e "\n# Deployer Configuration" >> "${SHELL_RC}"
            echo 'export PATH="/usr/local/bin:$PATH"' >> "${SHELL_RC}"
            echo 'export DEPLOYER_HOME="$HOME/.deployer"' >> "${SHELL_RC}"
        fi
    fi

    info "环境配置完成"
    info "请执行 'source ${SHELL_RC}' 使配置生效"
}

# 主函数
main() {
    echo "Deployer 安装程序"
    echo "================="

    # 执行安装步骤
    check_system
    check_ssh
    install_deps
    build_binary
    install_binary
    setup_env

    echo "================="
    info "安装成功！"
    info "执行 'deployer --help' 查看使用说明"
}

# 执行主函数
main
